<template>
  <div>
    <el-backtop target="#app .i-layout-content-main">
      <i class="el-icon-top"></i>
    </el-backtop>
    <el-form
      class="category_form_wrap"
      ref="formData"
      :model="formData"
      :rules="formRules"
      label-width="140px"
    >
      <!-- 分类名称 -->
      <el-form-item prop="categoryType" label="品类类型">
        <el-select
          v-model="formData.categoryType"
          placeholder="请选择品类类型"
          clearable
          :disabled="!!categoryLevel"
        >
          <el-option
            v-for="item in options.categoryType"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="categoryName" label="分类名称">
        <el-input
          v-model.trim="formData.categoryName"
          placeholder="请输入分类名称"
          class="shorter_input"
          show-word-limit
          :maxlength="20"
          @input="handleInputCategoryName"
        ></el-input>
      </el-form-item>
      <!-- 分类编码 -->
      <el-form-item prop="categoryNo" label="分类编码：">
        <el-input
          v-model.trim="formData.categoryNo"
          placeholder="请输入分类编码"
          class="shorter_input"
          show-word-limit
          :maxlength="15"
          :disabled="isResubmitPage()"
        ></el-input>
      </el-form-item>
      <!-- 位置 -->
      <el-form-item prop="position" label="位置：">
        <input-number
          v-model="formData.position"
          placeholder="请输入位置"
          controls-position="right"
          :precision="0"
          :min="0"
        ></input-number>
      </el-form-item>
      <el-form-item prop="labelNames" label="关联品类标签：">
        <el-input
          v-model="formData.labelNames"
          placeholder="请关联品类标签"
          class="shorter_input"
          readonly
        >
          <el-button
            slot="append"
            class="input_button_color"
            @click="handleChooseCateLabels"
          >选择</el-button
          >
        </el-input>
      </el-form-item>
      <!-- 是否启用 -->
      <el-form-item prop="state" label="是否启用：">
        <el-radio-group v-model="formData.state">
          <el-radio
            v-for="item in options.state"
            :key="item.label"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 描述 -->
      <el-form-item prop="categoryNote" label="描述：">
        <el-input
          v-model="formData.categoryNote"
          placeholder="请输入描述"
          class="shorter_input category_note"
          type="textarea"
          resize="none"
          show-word-limit
          :autosize="{ minRows: 2, maxRows: 4 }"
          :maxlength="50"
        ></el-input>
      </el-form-item>
      <template v-if="canShowAllItems()">
        <!-- 关联商品模板 -->
        <el-form-item prop="productTemplateNames" label="关联商品模板：">
          <el-input
            v-model="formData.productTemplateNames"
            placeholder="请选择关联商品模板"
            class="shorter_input"
            :disabled="!isAddPage"
            readonly
          >
            <el-button
              v-if="isAddPage"
              slot="append"
              class="input_button_color"
              @click="handleChooseProductTemplate"
            >选择</el-button
            >
          </el-input>
        </el-form-item>
        <!-- 关联计量单位 -->
        <el-form-item prop="unitNames" label="关联计量单位：">
          <el-input
            v-model="formData.unitNames"
            placeholder="请选择关联计量单位"
            class="shorter_input"
            readonly
          >
            <el-button
              slot="append"
              class="input_button_color"
              @click="handleChooseUnit"
            >选择</el-button
            >
          </el-input>
        </el-form-item>
        <!-- 关联验收事项 -->
        <el-form-item prop="acceptItemNames" label="关联验收事项：">
          <el-input
            v-model="formData.acceptItemNames"
            placeholder="请选择关联验收事项"
            class="shorter_input"
            readonly
          >
            <el-button
              slot="append"
              class="input_button_color"
              @click="handleChooseAcceptItem"
            >选择</el-button
            >
          </el-input>
        </el-form-item>
        <!-- 关联归类名称 -->
        <el-form-item prop="classificationNames" label="关联归类名称：">
          <el-input
            v-model="formData.classificationNames"
            placeholder="请选择关联归类名称"
            class="shorter_input"
            readonly
          >
            <el-button
              slot="append"
              class="input_button_color"
              @click="handleChooseClassification"
            >选择</el-button
            >
          </el-input>
        </el-form-item>
        <!-- 是否价格敏感 -->
        <el-form-item prop="isPriceSensitive" label="是否价格敏感：">
          <el-radio-group v-model="formData.isPriceSensitive">
            <el-radio
              v-for="item in options.default"
              :key="item.label"
              :label="item.value"
            >{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 商品资质类型 -->
        <el-form-item prop="productQualificationNames" label="商品资质类型：">
          <el-input
            v-model="formData.productQualificationNames"
            placeholder="请选择商品资质类型"
            class="shorter_input"
            readonly
          >
            <el-button
              slot="append"
              class="input_button_color"
              @click="handleSetProductQualification"
            >设置</el-button
            >
          </el-input>
        </el-form-item>
        <!-- 分类资质类型 -->
        <el-form-item prop="classifyQualificationNames" label="分类资质类型：">
          <el-input
            v-model="formData.classifyQualificationNames"
            placeholder="请选择分类资质类型"
            class="shorter_input"
            readonly
          >
            <el-button
              slot="append"
              class="input_button_color"
              @click="handleSetClassifyQualification"
            >设置</el-button
            >
          </el-input>
        </el-form-item>
       <template v-if="isShowAddRate">
          <!-- 售价指导加价率 -->
          <el-form-item prop="guideAddRate" label="售价指导加价率：">
            <input-number
              v-model="formData.guideAddRate"
              placeholder="请输入售价指导加价率"
              controls-position="right"
              :precision="2"
              :max="10"
              :min="0"
            ></input-number>
          </el-form-item>
          <!-- 畅销指导加价率 -->
          <el-form-item prop="sellWellAddRate" label="畅销指导加价率：">
            <input-number
              v-model="formData.sellWellAddRate"
              placeholder="请输入畅销指导加价率"
              controls-position="right"
              :precision="2"
              :max="10"
              :min="0"
            ></input-number>
          </el-form-item>
          <!-- 成交最低加价率 -->
          <el-form-item prop="limitAddRate" label="成交最低加价率：">
            <input-number
              v-model="formData.limitAddRate"
              placeholder="请输入成交最低加价率"
              controls-position="right"
              :precision="2"
              :max="10"
              :min="0"
            ></input-number>
          </el-form-item>
       </template>
      </template>
    </el-form>
    <el-divider></el-divider>
    <el-row type="flex" justify="center">
      <el-button @click="handleGoBack">返回</el-button>
      <el-button
        type="primary"
        :loading="submitBtnLoading"
        @click="handleSubmit"
      >提交</el-button>
    </el-row>
    <!-- 关联商品模板 -->
    <ProductTemplateLinked
      v-bind="$attrs"
      :visible.sync="productTemplateLinked.visible"
      @getProductTemplateInfo="getProductTemplateInfo"
    />
    <!-- 关联品牌 -->
    <BrandLinked
      v-bind="$attrs"
      :visible.sync="brandLinked.visible"
      @getLinkedBrandsInfo="getLinkedBrandsInfo"
    />
    <!-- 关联验收事项 -->
    <AcceptItemLinked
      v-bind="$attrs"
      :visible.sync="acceptItemLinked.visible"
      @getAcceptanceInfo="getAcceptanceInfo"
    />
    <!-- 关联归类名称 -->
    <ClassificationLinked
      v-bind="$attrs"
      :visible.sync="classificationLinked.visible"
      @getClassificationInfo="getClassificationInfo"
    />
    <!-- 商品资质类型 -->
    <QualificationType
      relType="1"
      dialogTitle="商品资质类型"
      :visible.sync="productQualification.visible"
      :dataSource="productQualification.dataSource"
      @getQualificationInfo="getQualificationInfoByProduct"
    />
    <!-- 分类资质类型 -->
    <QualificationType
      relType="2"
      dialogTitle="分类资质类型"
      :visible.sync="classifyQualification.visible"
      :dataSource="classifyQualification.dataSource"
      @getQualificationInfo="getQualificationInfoByClassify"
    />
    <!-- 关联计量单位 -->
    <MeasuringUnitLinked
      v-bind="$attrs"
      :visible.sync="measuringUnit.visible"
      @getMeasuringUnitInfo="getMeasuringUnitInfo"
    />
    <!-- 关联品类标签 -->
    <AssociateLabel
      :categoryUuid="uuid"
      :visible.sync="categoryLabels.visible"
      @confirm="getCategoryLabelsInfo"
    />
  </div>
</template>
<script>
import ProductTemplateLinked from '../ProductTemplateLinked';
import BrandLinked from '../BrandsLinked';
import AcceptItemLinked from '../AcceptItemLinked';
import ClassificationLinked from '../ClassificationLinked';
import QualificationType from '../QualificationType';
import MeasuringUnitLinked from '../MeasuringUnitLinked';
import InputNumber from '@/components/inputNumber/inputNumber';
import AssociateLabel from '@/components/Category/AssociateLabel';
import { formRules } from './constants';
import { CATEGORY_TYPE_OPTIONS } from '@/constants/basics';
export default {
  props: {
    categoryLevel: { // 当前品类等级，默认为一级
      type: String,
      default: ''
    },
    categoryType: { // 品类类型
      type: String,
      default: ''
    },
    qualificationTypes: { // 资质类型数据源（商品、类型）
      type: Object,
      default () {
        return {
          productResult: [],
          classifyResult: []
        };
      }
    },
    routerName: { // 返回路由name
      type: String,
      default: 'categoryList'
    },
    handleOk: { // 提交方法
      type: Function,
      default: () => {}
    },
    submitBtnLoading: { // 提交按钮loading
      type: Boolean,
      default: false
    },
    isAddPage: { // 是新增页面，默认是
      type: Boolean,
      default: true
    },
    dataSource: { // 表单数据源，编辑页面传入，新增启用默认数据
      type: Object,
      default () {
        return {
          categoryType: '', // 品类类型
          categoryName: '', // 分类名称
          categoryNo: '', // 分类编码
          labelNames: '', // 品类标签名
          position: null, // 位置
          state: '1', // 是否启用
          categoryNote: '', // 描述
          productTemplateNames: '', // 关联商品模板
          brandNames: '', // 关联品牌
          unitNames: '', // 关联计量单位
          acceptItemNames: '', // 关联验收事项
          classificationNames: '', // 关联归类名称
          isPriceSensitive: '', // 是否价格敏感
          productQualificationNames: '', // 商品资质类型
          classifyQualificationNames: '', // 关联归类名称
          guideAddRate: null, // 售价指导加价率
          sellWellAddRate: null, // 畅销指导加价率
          limitAddRate: null, // 成交最低加价率
        };
      }
    },
    uuid: { // 品类uuid
      type: String,
      default: ''
    },
  },
  components: {
    ProductTemplateLinked,
    BrandLinked,
    AcceptItemLinked,
    ClassificationLinked,
    QualificationType,
    MeasuringUnitLinked,
    InputNumber,
    AssociateLabel
  },
  data () {
    return {
      productTemplateLinked: {
        visible: false, // 弹框开关
        result: {}
      },
      categoryLabels: {
        visible: false, // 弹框开关
        result: {}
      },
      brandLinked: {
        visible: false, // 弹框开关
        result: {}, // 关联品牌所需入参categoryBrandRelList
      },
      measuringUnit: {
        visible: false, // 弹框开关
        result: {}
      },
      acceptItemLinked: {
        visible: false, // 弹框开关
        result: {}
      },
      classificationLinked: {
        visible: false, // 弹框开关
        result: {}
      },
      productQualification: { // 弹框开关
        visible: false,
        dataSource: [],
        result: []
      },
      classifyQualification: {
        visible: false,
        dataSource: [],
        result: []
      },
      formData: {},
      formRules: formRules,
      options: {
        default: [
          { label: '是', value: '1' },
          { label: '否', value: '2' }
        ],
        state: [
          { label: '启用', value: '1' },
          { label: '不启用', value: '2' }
        ],
        categoryType: CATEGORY_TYPE_OPTIONS
      }
    }
  },
  watch: {
    qualificationTypes: {
      immediate: true,
      deep: true,
      handler (data) {
        const { productResult, classifyResult } = data;
        this.productQualification.dataSource = productResult;
        this.productQualification.result = productResult;
        this.classifyQualification.dataSource = classifyResult;
        this.classifyQualification.result = classifyResult;
      }
    },
    categoryLevel (val) {
      if (!this.isOneOrTwoLevel(val)) { // 新增（二级增三级，三级增四级时需要初始化radio的值）
        this.initValueByRadio();
      }
    },
    dataSource: {
      immediate: true,
      deep: true,
      handler (data) {
        this.formData = { ...data };
      }
    },
    categoryType (val) { // 只有新增才会有
      this.formData.categoryType = val;
    }
  },
  computed: {
    // 是否展示三个加价率
    isShowAddRate () {
      if (this.isAddPage) return true // 新增页面
      if (this.$route?.query?.editStatus == '1') return true // 审核未通过-重新发起-新增类型
      return false
    }
  },
  methods: {
    // 是重新提交页面
    isResubmitPage () {
      return this.$route.query.pagesource == '1';
    },
    // 是根、一、二级品类
    isOneOrTwoLevel (val = this.categoryLevel) {
      return ['', '1', '2'].includes(val);
    },
    canShowAllItems () {
      if (this.$route.query.pagesource) { // 是编辑或者重新提交（只有四级类才展示全部表单内容）
        return this.categoryLevel === '4';
      }
      return !this.isOneOrTwoLevel(); // 新增（二级增三级，三级增四级展示全部表单内容）
    },
    /**
     * 初始化部分单选初始值
     * @isBasic 是否是基础表单；根、一、二级分类是，三、四级分类展示表单全部
    */
    initValueByRadio (isBasic = false) {
      if (isBasic) {
        this.formData.isPriceSensitive = '';
      } else {
        this.formData.isPriceSensitive = '2';
      }
    },
    // 提交
    handleSubmit () {
      /* 表单校验 */
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.handleOk(this.getResultBySubmit());
        } else {
          this.$message.warning('必填项不能为空！');
        }
      });
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: this.routerName })
    },
    // 输入分类名称 input事件
    handleInputCategoryName (val) {
      const regExp = /[`~!@#$%^&*()_+=<>?:"{}|,;'\\[\]·~！@#￥%……&*——+={}|《》？：“”【】、；‘’，。、]/g;
      this.formData.categoryName = val.replace(regExp, '').replace(/\s/g, '');
    },
    // 打开关联商品模板弹框
    handleChooseProductTemplate () {
      this.productTemplateLinked.visible = true;
    },
    // 打开关联品牌弹框
    handleChooseBrand () {
      this.brandLinked.visible = true;
    },
    // 打开关联验收事项弹框
    handleChooseAcceptItem () {
      this.acceptItemLinked.visible = true;
    },
    // 打开关联税类模板弹框
    handleChooseClassification () {
      this.classificationLinked.visible = true;
    },
    // 打开商品资质类型弹框
    handleSetProductQualification () {
      this.productQualification.visible = true;
    },
    // 打开分类资质类型弹框
    handleSetClassifyQualification () {
      this.classifyQualification.visible = true;
    },
    // 打开计量单位弹框
    handleChooseUnit () {
      this.measuringUnit.visible = true;
    },
    // 打开关联品类标签弹框
    handleChooseCateLabels () {
      this.categoryLabels.visible = true
    },
    // 获取关联模板信息
    getProductTemplateInfo (data) {
      this.formData.productTemplateNames = data.productTemplateNames;
      this.productTemplateLinked.result = data;
    },
    // 获取关联品牌信息
    getLinkedBrandsInfo (data) {
      const { brandNames } = data;
      this.formData.brandNames = brandNames;
      this.brandLinked.result = data;
    },
    // 获取关联计量单位信息
    getMeasuringUnitInfo (data) {
      this.formData.unitNames = data.unitNames;
      this.measuringUnit.result = data;
    },
    // 获取关联品类标签信息
    getCategoryLabelsInfo (data) {
      const { uuids = [], names = [] } = data ?? {}
      this.formData.labelNames = names.join(',')
      this.categoryLabels.result = { labelUuids: uuids }
    },
    // 获取验收事项信息
    getAcceptanceInfo (data) {
      this.formData.acceptItemNames = data.acceptItemNames;
      this.acceptItemLinked.result = data;
    },
    // 获取归类信息
    getClassificationInfo (data) {
      this.formData.classificationNames = data.classificationNames;
      this.classificationLinked.result = data;
    },
    // 获取商品资质类型信息
    getQualificationInfoByProduct (data) {
      this.formData.productQualificationNames = data.listQualificationNames;
      this.productQualification.result = data.listQualificationTypes;
    },
    // 获取分类资质类型信息
    getQualificationInfoByClassify (data) {
      this.formData.classifyQualificationNames = data.listQualificationNames;
      this.classifyQualification.result = data.listQualificationTypes;
    },
    // 获取提交结果
    getResultBySubmit () {
      const listQualificationTypes = [].concat(
        this.productQualification.result, this.classifyQualification.result
      );
      return {
        ...this.formData,
        ...this.productTemplateLinked.result,
        ...this.brandLinked.result,
        ...this.measuringUnit.result,
        ...this.acceptItemLinked.result,
        ...this.classificationLinked.result,
        ...this.categoryLabels.result,
        listQualificationTypes,
      }
    },
  }
}
</script>
<style lang="less" scoped>
.category_note {
  /deep/ .el-textarea__inner {
    padding-right: calc(3vw);
  }
}
/deep/.shorter_input.el-input--small {
  width: 70%;
}
.special_text_wrap {
  margin-left: 5px;
  color: #409EFF;
}
.input_button_color {
  color: #ffffff !important;
  background-color: #409EFF !important;
  &:hover{
    box-shadow: 2px 2px 2px #888888;
  }
}
</style>
